package com.shuohe.service.impl.system.user;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.bstek.uflo.process.assign.Entity;
import com.bstek.uflo.process.assign.PageQuery;
import com.shuohe.dao.system.user.DepartmentDao;
import com.shuohe.dao.system.user.PositionDao;
import com.shuohe.dao.system.user.UserDao;
import com.shuohe.entity.system.dto.DeptDto;
import com.shuohe.entity.system.dto.UserDto;
import com.shuohe.entity.system.user.Department;
import com.shuohe.entity.system.user.User;
import com.shuohe.service.system.user.UserService;
import com.shuohe.service.system.user.UserService.DepTmp;
import com.shuohe.service.util.sql.EasyuiServiceImpl;
import com.shuohe.util.db.DbQuerySql;
import com.shuohe.util.easyuiBean.EasyUiDataGrid;
import com.shuohe.util.encryption.MD5Utils;
import com.shuohe.util.json.Json;
import com.shuohe.util.returnBean.ReturnBean;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private PositionDao positionDao;
	
	@Autowired
	private DepartmentDao departmentDao;
  
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
    @Resource
    private EasyuiServiceImpl easyUiDto;
    
    
    private Logger loger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    
	@Override
	public boolean delete(User user) {
		// TODO Auto-generated method stub
		userDao.delete(user);
		return false;
	}

	@Override
	public User check(String name, String password) {
		// TODO Auto-generated method stub
		return userDao.check(name, MD5Utils.md5(password));
	}

	@Override
	public boolean save(User user) {
		// TODO Auto-generated method stub
		/*
		String uuid = UUID.randomUUID().toString();
		org.activiti.engine.identity.User activiti_user = this.identityService.newUser(uuid);
		activiti_user.setLastName("");
		activiti_user.setFirstName(user.getActual_name());
		this.identityService.saveUser(activiti_user);	
		// 设置与用户组的关系
		Position position = positionDao.findById(user.getPosition_id());
		this.identityService.createMembership(activiti_user.getId(),position.getActiviti_uuid());
		
		//保存系统用户信息
		user.setActiviti_uuid(uuid);*/
		
		userDao.save(user);
		
		return true;
	}

	@Override
	public boolean update(User user) {
		userDao.save(user);
		return true;
	}

	@Override
	public EasyUiDataGrid getUserByDepartment(String department,String rows,String page) {
		// TODO Auto-generated method stub
		
		String sql = "";
		String count_sql = "";
		sql += "SELECT u.*, p.text position,d.text as dept,s.text as state FROM db_system_user_user u "
				+ " LEFT JOIN db_system_user_position p on u.position_id = p.id "
				+ " left join db_system_user_department d on u.department_id = d.id "
				+ " LEFT JOIN db_system_user_status s on u.status = s.id where 1= 1 ";
		sql += DbQuerySql.AEqualToB(" and u.department_id", department);
		sql += DbQuerySql.limit(page, rows);
		
		count_sql += "SELECT u.*, p.text position,d.text as dept,s.text as state FROM db_system_user_user u "
				+ " LEFT JOIN db_system_user_position p on u.position_id = p.id "
				+ " left join db_system_user_department d on u.department_id = d.id "
				+ " LEFT JOIN db_system_user_status s on u.status = s.id where 1= 1 ";
		count_sql += DbQuerySql.AEqualToB(" and u.department_id", department);
		
		return easyUiDto.getEasyUiDataGrid(sql, count_sql);
	}

	@Override
	public User findById(int id) {
		// TODO Auto-generated method stub
		return userDao.findById(id);
	}

	@Override
	public User findByActivitiUUID(String activiti_uuid) {
		// TODO Auto-generated method stub
		return userDao.findByActivitiUUID(activiti_uuid);
	}

	@Override
	public List<User> findByPositionId(int position_id) {
		return userDao.findByPositionId(position_id);
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}
	
	
	private List<DepTmp> getDepartments()
	{ 
		List<DepTmp> ret = new ArrayList<DepTmp>();
		List<Department> xxx = departmentDao.findAll();
		for(Department d:xxx)
		{
			ret.add(new DepTmp(
					d.getId(),
					d.getParent_id(),
					d.getText(),
					false,
					null
			));
		}  		
		return ret;
	}
	private List<DepTmp> getUsers()
	{
		List<DepTmp> ret = new ArrayList<DepTmp>();       
		List<User> users = userDao.findAll();    
		for(User u:users)
		{
			ret.add(new DepTmp(
					u.getId(),
					u.getDepartment_id(),
					u.getActual_name(),
					true,
					null
			));		
		}
		return ret;
	}
//	private List<DeptDto> getChildsManyGroupDepTmp(List<Map<String, Object>> list,int pid)
//	{  
//		List<DeptDto> arr = new ArrayList<DeptDto>();  
//		List<Map<String, Object>> groupLidt = new ArrayList<Map<String, Object>>();
//		DeptDto dd = new DeptDto();
//		List<UserDto> userArr = new ArrayList<UserDto>();
//		for(Map<String, Object> location : list){
//			loger.info("pid=="+pid);
//			loger.info("deptid=="+location.get("department_id"));
//		    if(pid == (int)location.get("parent_id")){
//		    	dd.setDeptId((Integer)location.get("department_id"));
//		    	dd.setDeptName((String)location.get("text"));
//		    	dd.setParentId(pid);
//		    	UserDto ud = new UserDto();
//		    	ud.setId((Integer)location.get("id"));
//		    	ud.setUserName((String)location.get("actual_name"));
//		    	userArr.add(ud);
//		    	dd.setUserlist(userArr);
//		    	groupLidt.add(location);
//		    	dd.setDeptDtoList(getChildsManyGroupDepTmp(groupLidt, (Integer)location.get("department_id")));   
//		        arr.add(dd);   
//		    }  
//		}  
//		//System.out.println(arr.toString());
//		loger.info("dd = "+Json.toJson(dd));
//		return arr;  
//	} 
	
	private List<DepTmp> getChildsManyGroupDepTmp(List<DepTmp> list,int pid)
	{  
		List<DepTmp> arr = new ArrayList<DepTmp>();  
		for(DepTmp location : list){  
		    if(pid == location.getParent_id()){  
		        location.setChildren(getChildsManyGroupDepTmp(list, location.getId()));    
		        arr.add(location);   
		    }  
		}  
		return arr;  
	}  
	
	
	@Override
	public List<DepTmp> getEasyUiTreeDepAndUser() 
	{
		return getEasyUiTreeDepAndUser(0);
	}

	@Override
	public ReturnBean isUserExist(int id) {
		// TODO Auto-generated method stub
		User user = findById(id);
		if(user == null) return new ReturnBean(false,"用户不存在"); 
		else	 return new ReturnBean(true,"用户存在");
	}
	
	@Override
	public void page(PageQuery<Entity> query){
		int current = query.getPageIndex()-1;
		int size = query.getPageSize();
		Pageable page = new PageRequest(current,size);
		Page<User> user = userDao.page(page);
		List<Entity> lt = new ArrayList<Entity>();
		for(User u: user.getContent()) {
			Entity et = new Entity(String.valueOf(u.getId()), u.getName());
			lt.add(et);
		}
		query.setId("1");
		query.setName("所有用户");
		query.setPageIndex(current+1);
		query.setPageSize(size);
		query.setTree(false);
		query.setResult(lt);
		query.setRecordCount(userDao.findAll().size());
	}
	
	@Override
	public void page1(PageQuery<Entity> query){
		int current = query.getPageIndex();
		int size = query.getPageSize();
		List<User> user = userDao.findByPositionId(9);
		List<Entity> lt = new ArrayList<Entity>();
		for(User u: user) {
			Entity et = new Entity(String.valueOf(u.getId()), u.getName());
			lt.add(et);
		}
		query.setId("1");
		query.setName("所有用户");
		query.setPageIndex(current+1);
		query.setPageSize(size);
		query.setTree(false);
		query.setResult(lt);
		query.setRecordCount(user.size());
	}
	
	//获取所有用户列表
	public List<Map<String, Object>> getAllUser(){
		String sql = "SELECT db_system_user_user.id, db_system_user_user.actual_name,"
				+ " db_system_user_user.department_id,db_system_user_department.text,"
				+ " db_system_user_department.parent_id FROM db_system_user_user LEFT JOIN "
				+ " db_system_user_department ON db_system_user_department.id = db_system_user_user.department_id";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		System.out.println(list);
		System.out.println(list.size()+"======================");
		return list;
	}

	@Override
	public ReturnBean isUserExist(String name) {
		List<User> list = userDao.findByNameList(name);
		if(list == null) return new ReturnBean(false,"不存在同名的用户");
		if(list.size()>0) return new ReturnBean(true,"存在同名的用户");
		else
		{
			return new ReturnBean(false,"不存在同名的用户");
		}
	}

	@Override
	public User findByName(String name) {
		return userDao.findByName(name);
	}

	@Override
	public List<DepTmp> getEasyUiTreeDepAndUser(int department_id) {
		  List<DepTmp>  ret = new ArrayList<DepTmp>();            
		  List<DepTmp> list1 = getDepartments();
		  List<DepTmp> list2 = getUsers();        
		  for(DepTmp d:list1)
		  {
		  		ret.add(d);
		  }
		  for(DepTmp d:list2)
		  {
		  		ret.add(d);
		  }                   
		  ret = getChildsManyGroupDepTmp(ret,department_id);
		  return ret;
	}
	
	
}
